<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { Advertisement } from '@/api/modules/advertisements'
import type { FormInstance, FormRules } from 'element-plus'
import apiAdvertisement from '@/api/modules/advertisements'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

const updateImg = ref(false)
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  advertisementId: route.params.id as string | number ?? '',
  advertisementName: '',
  advertisementNameEn: '',
  advertisementTitle: '',
  advertisementTitleEn: '',
  advertisementDescribe: '',
  advertisementDescribeEn: '',
  advertisementUrl: '',
  typeName: '',
  typeNameEn: '',
  createdAt: '',
  updatedAt: '',
  advertisementHttp: '',
  status: 0, // 默认值为 "否"
})

const formRules = ref<FormRules>({
  advertisementName: [
    { required: true, message: '请输入广告名称', trigger: 'blur' },
  ],
  province: [
    { required: true, message: '请输入广告主题', trigger: 'blur' },
  ],
  city: [
    { required: true, message: '请输入详细描述', trigger: 'blur' },
  ],
  level: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
  ],
})

onMounted(() => {
  if (form.value.advertisementId !== '') {
    getInfo()
  }
})

function getInfo() {
  loading.value = true
  apiAdvertisement.detail(form.value.advertisementId).then((res: any) => {
    loading.value = false
    const data = res.data.data // 提取数据
    // 完整映射所有字段
    form.value.advertisementId = data.advertisementId
    form.value.advertisementName = data.advertisementName
    form.value.advertisementNameEn = data.advertisementNameEn
    form.value.advertisementTitle = data.advertisementTitle
    form.value.advertisementTitleEn = data.advertisementTitleEn
    form.value.advertisementDescribe = data.advertisementDescribe
    form.value.advertisementDescribeEn = data.advertisementDescribeEn
    form.value.advertisementUrl = data.advertisementUrl
    form.value.typeName = data.typeName
    form.value.typeNameEn = data.typeNameEn
    form.value.createdAt = data.createdAt
    form.value.updatedAt = data.updatedAt
    form.value.advertisementHttp = data.advertisementHttp
    form.value.status = data.status
  })
}

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        // 构造符合 Advertisement 接口的对象
        const advertisementData: Advertisement = {
          advertisementId: Number(form.value.advertisementId),
          advertisementName: form.value.advertisementName,
          advertisementNameEn: form.value.advertisementNameEn,
          advertisementTitle: form.value.advertisementTitle,
          advertisementTitleEn: form.value.advertisementTitleEn,
          advertisementDescribe: form.value.advertisementDescribe,
          advertisementDescribeEn: form.value.advertisementDescribeEn,
          advertisementUrl: form.value.advertisementUrl,
          typeName: form.value.typeName,
          typeNameEn: form.value.typeNameEn,
          createdAt: form.value.createdAt,
          updatedAt: form.value.updatedAt,
          advertisementHttp: form.value.advertisementHttp,
          status: Number(form.value.status),
        }
        if (form.value.advertisementId === '') {
          apiAdvertisement.create(advertisementData).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
        else {
          form.value.advertisementId = Number(form.value.advertisementId)
          apiAdvertisement.edit(advertisementData).then(() => {
            ElMessage.success({
              message: '编辑成功',
            })
            goBack()
          })
        }
      }
    })
  })
}
function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'advertisement' })
  }
  else {
    router.push({ name: 'advertisement' })
  }
}

// 上传广告宣传图
async function handleLogoSuccess(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await apiAdvertisement.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.advertisementUrl = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'advertisementManagementCreate' ? '新增广告' : '编辑广告'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <ElFormItem label="广告名称" prop="advertisementName">
          <ElInput v-model="form.advertisementName" placeholder="请输入广告名称" />
        </ElFormItem>

        <ElFormItem label="广告英文名称" prop="advertisementNameEn">
          <ElInput v-model="form.advertisementNameEn" placeholder="请输入广告英文名称" />
        </ElFormItem>

        <ElFormItem label="广告主题" prop="advertisementTitle">
          <ElInput v-model="form.advertisementTitle" placeholder="请输入广告主题" />
        </ElFormItem>

        <ElFormItem label="广告英文主题" prop="advertisementTitleEn">
          <ElInput v-model="form.advertisementTitleEn" placeholder="请输入广告英文主题" />
        </ElFormItem>

        <ElFormItem label="广告详细描述" prop="advertisementDescribe">
          <ElInput v-model="form.advertisementDescribe" placeholder="请输入广告详细描述" />
        </ElFormItem>

        <ElFormItem label="广告英文详细描述" prop="advertisementDescribeEn">
          <ElInput v-model="form.advertisementDescribeEn" placeholder="请输入广告英文详细描述" />
        </ElFormItem>

        <ElFormItem label="广告宣传图" prop="advertisementUrl">
          <ImageUpload v-model="form.advertisementUrl" :loading="updateImg" action="" name="advertisementUrl" :width="150" :height="150" :http-request="handleLogoSuccess" />
        </ElFormItem>

        <ElFormItem label="广告分类名称" prop="typeName">
          <ElInput v-model="form.typeName" placeholder="请输入广告的分类名称" />
        </ElFormItem>

        <ElFormItem label="广告分类英文名称" prop="typeNameEn">
          <ElInput v-model="form.typeNameEn" placeholder="请输入广告的分类英文名称" />
        </ElFormItem>

        <ElFormItem label="广告跳转地址" prop="advertisementHttp">
          <ElInput v-model="form.advertisementHttp" placeholder="请输入广告的跳转地址" />
        </ElFormItem>

        <ElFormItem label="是否启动广告" prop="status">
          <ElSwitch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
            inline-prompt
          />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
